{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='HOME'></a>\n",
    "# CHAPTER 2 Numbers, Strings,and Variables\n",
    "## Python的基本元素：數字，字串和變量\n",
    "\n",
    "* [2.1 變數 名稱 物件](#Variables_Names_Objects)\n",
    "* [2.2 數字](#Numbers)\n",
    "* [2.3 字串](#Strings)\n",
    "\n",
    "\n",
    "Python內建的型態有\n",
    "* 布林值 Boolean  (True 、 False)\n",
    "* 整數 Integer\n",
    "* 浮點數 Float (可用科學記號表示法 ex. 1.0e3 = 1000.0)\n",
    "* 字串 String (字元組成的陣列)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "------\n",
    "<a id='Variables_Names_Objects'></a>\n",
    "## 2.1 變數 名稱 物件\n",
    "[回目錄](#HOME)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python為物件導向作為設計，所有的數據皆為Objcet，詳細的物件導向觀念可參考wiki中的介紹或是書中的介紹。  \n",
    "其中要特別注意所謂的針對某個特定物件型別內建method上的使用，  \n",
    "例如string型別內建upper函數，可以把文字轉成大寫，則要使用上的方法為__string.upper()__，  \n",
    "若是一個一般的內建method或是使用者自行建立的function，  \n",
    "例如__len()__，則使用上的方法為 __len('abc')__，  \n",
    "所以在學習Python時，需要清楚了解此function是針對某個型別的內建還是一般狀況。  \n",
    "\n",
    "其中要注意的是Python為強型別(Strongly typed)，也就是說在執行 '1' + 2，會出現TypeError，並不會出現3或是'12'的結果，所以進行不同型別之間的處理可以使用 int('1') + 2 = 3或是 '1' + str(2) = '12'來作為處理。\n",
    "\n",
    "跟大多數語言一樣，再給定變數數值是使用 '=' 來賦予值，在Python中變數不用宣告，並且還有一個特性為，變數在記憶體位置中僅僅像是標籤一般，對某個記憶體位置做貼標籤功能，在變數改變內容時，記憶體內的值不會改變，而是變數標籤貼到其他記憶體位置上。因此Python不用宣告變數型別，故可以改變變數內的型別，所以可以使用_type(變數)_做為檢測變數現在的型別。\n",
    "\n",
    "變數的命名不外乎就是只能大小寫英文字母、 數字與底線(_)，且不能以數字開頭，相關保留關鍵字如下，請勿作為變數名稱使用。\n",
    "\n",
    "\n",
    "![Alt text](http://i.imgur.com/vS3VxFe.png \"保留關鍵字\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "------\n",
    "<a id='Numbers'></a>\n",
    "## 2.2 數字\n",
    "[回目錄](#HOME)\n",
    "\n",
    "基本運算符號如下\n",
    "\n",
    "|符號|解釋|用法|\n",
    "|--|--|--|\n",
    "|+|加法|2 + 3 = 5|\n",
    "|-|減法|2 - 3 = -1|\n",
    "|\\*|乘法|2 * 3 = 6|\n",
    "|/|浮點數除法|3 / 2 = 1.5|\n",
    "|//|整數除法 (商數)|3 // 2 = 1|\n",
    "|%|餘數|3 % 2 = 1|\n",
    "|\\*\\*|次方|2 \\*\\* 3 = 8|\n",
    "\n",
    "\n",
    "對於正整數的操作，比較要注意的為0不可以放置在數字前端，如 a = 05 會出現SyntaxError。  \n",
    "於整數使用'/'除法上也會得到浮點數結果，並不需要特別轉換成浮點數再做除法運算。\n",
    "\n",
    "其餘運算規則與用法詳細請看書本介紹(ex. a = a + 1可以寫成 a += 1 等等)  \n",
    "數字型別轉換可以用__int()__，裡面不允許有非數字出現，浮點數會無條件捨去，其中python允許使用__int(98.7) = 98__，但__int('98.7')__則會出現錯誤，這點要多加小心。\n",
    "\n",
    "最為重要的一點為Python3之後沒有溢位問題，意旨儲存整數大小無上限，取決於自身記憶體限制。\n",
    "\n",
    "轉換成浮點數可以使用__float()__。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "------\n",
    "<a id='Strings'></a>\n",
    "## 2.3 字串\n",
    "[回目錄](#HOME)\n",
    "\n",
    "Python3支援Unicode!!!! 表示可以顯示中文等等，檔案編碼方式記得選擇Unicode  \n",
    "使用單或雙引號皆可以創建字串，若要在字串中包含單雙引號只要  \n",
    "用相反的作為外框  \n",
    "使用跳脫字元\\' \\\"  \n",
    "連續使用三次即可(單,雙引號都可以)\n",
    "\n",
    "三個單引號'''還可以用再多行字串的建立，一般常用於多行註解上使用。  \n",
    "在使用print()指令時，會自動將跳脫字元轉換成正確的顯示方式(ex. \\n轉換成跳行等等)  \n",
    "並且會在變數之間插入一空白\n",
    "\n",
    "```Python\n",
    "print('a','b','c') # 'a' 'b' 'c'\n",
    "```\n",
    "\n",
    "可以使用__str()__將其餘類別轉換成字串型態。\n",
    "\n",
    "字串相連接時可以使用 + 號或是直接把兩字串擺在前後即可。( print('a'+'b')   print('a''b')  都可以得到 'ab'的結果 )  \n",
    "使用\\*可以快速建立重複字串。\n",
    "\n",
    "```Python\n",
    "print('a' * 5) # 'aaaaa'\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b\n",
      "d\n"
     ]
    }
   ],
   "source": [
    "#前述提到字串為字元的陣列，故可以使用[ ]來提取特定位置之字元，(相關的容器介紹在CH3)\n",
    "\n",
    "a = 'bcd'    \n",
    "print(a[0]) #'b' \n",
    "print(a[-1]) #'d'\n",
    "\n",
    "#index從0開始，-1為最後一個字元"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "更多的提取方法如下\n",
    "\n",
    "|用法|說明|\n",
    "|--|--|\n",
    "|[ : ]|提取全部|\n",
    "|[start : ]|提取 start 至結束|\n",
    "|[ : end]|提取開頭到 end - 1|\n",
    "|[start : end]|提取 start 至 end - 1|\n",
    "|[start : end : step]|提取 start 至 end - 1，間隔為 step (step為負的時則從右邊開始，start與end需反過來擺放)|\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "edcba\n",
      "dcb\n"
     ]
    }
   ],
   "source": [
    "a = 'abcde'\n",
    "print(a[::-1]) #'edcba' 可以變成反序排列\n",
    "print(a[-2:0:-1]) #'dcb'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "其中變數內的字串是不能替換內容(因為容器為類似TUPLES的型態，CH3會說明)，\n",
    "若要替換內容，則可以使用重組或是 __string.replace()__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Penny\n",
      "Penny\n"
     ]
    }
   ],
   "source": [
    "name = 'Henny'\n",
    "#name[0] = 'P' #錯誤!!!!!!\n",
    "a = name.replace('H', 'P') #'Penny'\n",
    "print(a)\n",
    "print('P' + name[1:]) #'Penny'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "__len()__ 可以獲得長度"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = 'abc'\n",
    "len(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "__string.split()__可以分割字串成list，( )內可以指定符號，預設會切割\\n(換行) 、 \\t(tab)與空格三種"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['get gloves', 'get mask', 'give cat vitamins', 'call ambulance']\n",
      "['get', 'gloves,get', 'mask,give', 'cat', 'vitamins,call', 'ambulance']\n"
     ]
    }
   ],
   "source": [
    "todos = 'get gloves,get mask,give cat vitamins,call ambulance'\n",
    "print(todos.split(','))\n",
    "print(todos.split())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "__'符號'.join()__可以合併list成字串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Yeti, Bigfoot, Loch Ness Monster'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "crypto_list = ['Yeti', 'Bigfoot', 'Loch Ness Monster']\n",
    "', '.join(crypto_list)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "__string.startswith()__ 與 __string.endswith()__ 分別可以檢查開頭與結束字串是否為特定字串，回傳__True__或__False__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "poem = 'abcdef'\n",
    "print(poem.startswith('ab'))\n",
    "print(poem.endswith('eef'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "__string.find()__ 與 __string.rfind()__ 可以查詢第一次與最後一次出現搜尋字串的index，__string.count()__可以查詢字串出現次數"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "6\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "poem = 'abcdefbcd'\n",
    "print(poem.find('bc'))\n",
    "print(poem.rfind('bc'))\n",
    "print(poem.count('bc'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "__string.isalnum()__可以查詢字串中是否都是字母或數字，回傳__True__或__False__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "poem = 'abc@def'\n",
    "poem.isalnum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a duck goes into a bar\n",
      "A duck goes into a bar...\n",
      "A Duck Goes Into A Bar...\n",
      "A DUCK GOES INTO A BAR...\n",
      "a duck goes into a bar...\n",
      "A DUCK GOES INTO A BAR...\n",
      "  a duck goes into a bar...   \n",
      "a duck goes into a bar...     \n",
      "     a duck goes into a bar...\n",
      "a marmoset goes into a bar...\n",
      "a famous duck goes into a famous bar...\n"
     ]
    }
   ],
   "source": [
    "#其餘還有一些方便的string內建function可以使用\n",
    "\n",
    "setup = 'a duck goes into a bar...'\n",
    "print(setup.strip('.'))                      #刪除結尾特定符號 'a duck goes into a bar'\n",
    "print(setup.capitalize())                    #字串第一個字元大寫 'A duck goes into a bar...'\n",
    "print(setup.title())                         #每個單字開頭大寫 'A Duck Goes Into A Bar...'\n",
    "print(setup.upper())                         #全部大寫 'A DUCK GOES INTO A BAR...'\n",
    "print(setup.lower())                         #全部小寫 'a duck goes into a bar...'\n",
    "print(setup.swapcase())                      #大小寫交換 'a DUCK GOES INTO A BAR...'\n",
    "print(setup.center(30))                      #將字串中心移動至30個字元的中間 '  a duck goes into a bar...   '\n",
    "print(setup.ljust(30))                       #左對齊 'a duck goes into a bar...     '\n",
    "print(setup.rjust(30))                       #右對齊 '     a duck goes into a bar...'\n",
    "print(setup.replace('duck', 'marmoset'))     #'a marmoset goes into a bar...'\n",
    "print(setup.replace('a ', 'a famous ', 100)) #只替換前100個'a '"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [Root]",
   "language": "python",
   "name": "Python [Root]"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
